import DashboardLayout from "@/layouts/dashboard";
import PageError from "@/pages/system/error/PageError";
import Login from "@/pages/system/login/Login";
import ProtectedRoute from "@/router/components/protected-route";
import { usePermissionRoutes } from "@/router/hooks";
import { ERROR_ROUTE } from "@/router/routes/error-routes";
import { ErrorBoundary } from "react-error-boundary";
import { Navigate, type RouteObject, createHashRouter } from "react-router";
import { RouterProvider } from "react-router/dom";
import type { AppRouteObject } from "#/router";

const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env;

/**
 * 公共路由
 */
const PUBLIC_ROUTE: AppRouteObject = {
	path: "/login",
	element: (
		<ErrorBoundary FallbackComponent={PageError}>
			<Login />
		</ErrorBoundary>
	),
};

/**
 * 未匹配路由时的重定向
 */
const NO_MATCHED_ROUTE: AppRouteObject = {
	path: "*",
	element: <Navigate to="/404" replace />,
};

/**
 * 路由配置
 */
export default function Router() {
	const permissionRoutes = usePermissionRoutes();

	const PROTECTED_ROUTE: AppRouteObject = {
		path: "/",
		element: (
			<ProtectedRoute>
				<DashboardLayout />
			</ProtectedRoute>
		),
		children: [{ index: true, element: <Navigate to={HOMEPAGE} replace /> }, ...permissionRoutes],
	};

	const routes = [PUBLIC_ROUTE, PROTECTED_ROUTE, ERROR_ROUTE, NO_MATCHED_ROUTE] as RouteObject[];

	// 使用createHashRouter创建基于哈希的路由器
	// 参数routes是之前定义的路由配置数组
	// 使用哈希路由的原因：
	// 1. 适用于静态服务器部署，无需服务器端路由配置
	// 2. URL中的哈希部分不会发送到服务器，完全由前端处理
	// 3. 兼容性更好，支持老旧浏览器
	// 注意：生产环境建议使用BrowserRouter以获得更友好的URL
	const router = createHashRouter(routes);

	return <RouterProvider router={router} />;
}
